<?php
class basic{
    protected $data=array();       //输送到模板中的变量

    function basic(){
        //echo "2333这是基础模块";
    }

    function run(){
        /* 设定全局变量 */
        $controller = (isset($_GET['c'])&&!empty($_GET['c']))?$_GET['c']:'index';
        $action     = (isset($_GET['a'])&&!empty($_GET['a']))?$_GET['a']:'index';

        /* 初始化控制器c */
        if(file_exists(APP_PATH.$controller.'.class.php')){
            include_once(APP_PATH.$controller.'.class.php');
            $c=new $controller();
        }
        else{
            echo "出错了哦~不存在".$controller.'控制器';
            return false;
        }

        /* 初始化具体操作a */
        if(!method_exists($c,$action)){
            echo "出错了哦~不存在".$action.'操作';
        }
        else {
            $c->$action();
        }
    }
    
    /* 获取文件内容 */
    private function get_content($filename)
    {
        if(file_exists($filename)){
            $fp=fopen($filename,"r");
            $data="";
            while(!feof($fp)){
                $data.=fread($fp,4096);
            }
            fclose($fp);

            return $data;
        }
        else{
            echo "未找到模板文件".$filename;
        }
        
        return false;
    }

    /* 执行脚本,并且返回结果 */
    function exec($filename,&$output){
        exec('sudo sh '.$filename,$output,$return);
        return $return;
    }

    function display($data=''){
        if(!empty($data)){
            $page=$this->get_content($data);
        }
        else{
            $controller=empty($_GET['c'])?'index':$_GET['c'];
            $action=empty($_GET['a'])?'index':$_GET['a'];
            $page=$this->get_content(TEMPLATE_PATH.$controller.'/'.$action.'.html');
        }
        echo $this->parse($page,$this->data);

        exit();
    }

    private function parse($page,$data){    //模板解析
        /*先解析include*/
        preg_match_all('/{{\s*include\s*(\S+)\s*}}/i', $page, $match);
        foreach ($match[1] as $key => $value) {
            $page=preg_replace('/{{\s*include\s*'.addslashes($value).'\s*}}/i', $this->get_content($value), $page);
        }

        /*解析for*/
        /*$page=preg_replace('/{%\s*foreach\s*(\$\S+){3}\s*%}([\s\S]+){%\s*endforeach\s*%}/i', 
            '<?php foreach(${1} as ${2} => ${3}){?> ${4} <?php }?>', $page);

        /*解析单个变量*/
        foreach ($data as $key => $value) {
            $page=preg_replace('/{{\s*'.$key.'\s*}}/i',$value,$page);
        }

        return $page;
    }

    function assign($name,$data){
        $this->data[$name]=$data;
    }

    function success($info=''){
        echo '<div style="font-size:30px">; ) success! <br/>'.$info.'<br/>正在返回上一页</div><script>window.setInterval("history.go(-1)","4000");</script>';
    }

    function error($info){
        echo "操作失败";
    }
}